#include "modifypd.h"
#include "ui_modifypd.h"
#include "widget.h"

#include <QHostAddress>

ModifyPd::ModifyPd(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ModifyPd)
{
    ui->setupUi(this);

//    QPalette pal = this->palette();
//    pal.setBrush(QPalette::Background,QBrush(QPixmap("://p3.jpeg")));
//    setPalette(pal);
    setWindowTitle("用户修改密码");
    ui->newpd->setEchoMode(QLineEdit::Password);
    ui->newpd2->setEchoMode(QLineEdit::Password);
    m_tcp = new QTcpSocket;
    m_tcp->connectToHost(QHostAddress("127.0.0.1"), 8888);

    connect(ui->pushButton, &QPushButton::clicked, this, &ModifyPd::update_pd);
    connect(ui->pushButton_2, &QPushButton::clicked, this, [=]{
        Widget *w = new Widget;
        w->show();
        this->close();
    });

}

ModifyPd::~ModifyPd()
{
    delete ui;
}

void ModifyPd::update_pd()
{
    QString uid = ui->id->text();
    QString upd = ui->newpd->text();
    QString upd2 = ui->newpd2->text();
    if (QString::compare("", uid)==0||QString::compare("",upd)==0||QString::compare("",upd2)==0) {
        QMessageBox::information(this, "错误", "帐号或密码不能为空");
        return ;
    }
    if (QString::compare(upd, upd2) != 0) {
        QMessageBox::information(this, "错误", "两次输入的密码不相同");
        return ;
    }
    int type = 3;
    int uid_len = uid.size();
    int upd_len = upd.size();
    m_tcp->write((char*)&type, 4);
    m_tcp->write((char*)&uid_len, 4);
    m_tcp->write(uid.toUtf8());
    m_tcp->write((char*)&upd_len, 4);
    m_tcp->write(upd.toUtf8());
    connect(m_tcp, &QTcpSocket::readyRead, this, [=](){
        int type;
        m_tcp->read((char*)&type, 4);
        if (type == 3) {
            QByteArray data = m_tcp->readAll();
            QString ack = data;
            qDebug() << "ack: " << ack;
            if (QString::compare("nofind", ack) == 0) {
                QMessageBox::information(this, "错误", "帐号不存在");
            } else {
                QMessageBox::information(this, "提示", "修改密码成功");
                Widget *w = new Widget;
                w->show();
                this->close();
            }
        }
    });
}

